//
//  UIViewController+NavigationBar.m
//  OASDK_Works
//
//  Created by ChenJie on 5/17/20.
//  Copyright © 2020 Mist. All rights reserved.
//

#import "UIViewController+NavigationBar.h"
#import <objc/runtime.h>
#import "OASDK.h"

@implementation UIViewController (NavigationBar)

/*
 * oa_isHideNavigationBar
 */
- (BOOL)oa_isHideNavigationBar{
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (void)oa_setIsHideNavigationBar:(BOOL)oa_isHideNavigationBar {
    objc_setAssociatedObject(self, @selector(oa_isHideNavigationBar), @(oa_isHideNavigationBar), OBJC_ASSOCIATION_ASSIGN);
}


/*
 *
 */
+ (void)SwizzleMethodWithClass:(Class)class
              originalSelector:(SEL)originalSelector
              swizzledSelector:(SEL)swizzledSelector {
    Method originalMethod = class_getInstanceMethod(class, (originalSelector));
    Method swizzledMethod = class_getInstanceMethod(class, (swizzledSelector));
    if (!class_addMethod((class),
                         (originalSelector),
                         method_getImplementation(swizzledMethod),
                         method_getTypeEncoding(swizzledMethod))) {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    } else {
        class_replaceMethod((class),
                            (swizzledSelector),
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    }
}

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        [self SwizzleMethodWithClass:UIViewController.class
                    originalSelector:@selector(viewWillAppear:)
                    swizzledSelector:@selector(oa_viewWillAppear:)];
        
        [self SwizzleMethodWithClass:UIViewController.class
                    originalSelector:@selector(viewWillDisappear:)
                    swizzledSelector:@selector(oa_viewWillDisappear:)];
        
    });
    
}

- (void)oa_viewWillAppear:(BOOL)animated {
    [self oa_viewWillAppear:animated];
    
    if (self.oa_isHideNavigationBar) {
        self.navigationController.navigationBarHidden = YES;
    }
    
    OALogFunction;
}

- (void)oa_viewWillDisappear:(BOOL)animated {
    [self oa_viewWillDisappear:animated];
    
    if (self.oa_isHideNavigationBar) {
        self.navigationController.navigationBarHidden = NO;
    }
    
    OALogFunction;
}

@end
